package me.itsoo.artemis.framework.repository.mapper;

import me.itsoo.artemis.framework.core.util.CollectionUtils;
import me.itsoo.artemis.framework.repository.executor.BoundSql;
import me.itsoo.artemis.framework.repository.mapper.condition.PageCondition;
import me.itsoo.artemis.framework.repository.mapper.condition.QueryCondition;
import me.itsoo.artemis.framework.repository.mapper.resource.QueryResource;
import me.itsoo.artemis.framework.repository.page.PageResult;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * DemoMapSqlMapper
 *
 * @author zxy
 * @version 0.0.1
 * @since 2023/5/11
 */
@SuppressWarnings("rawtypes")
public class DemoMapSqlMapper extends AbstractSqlMapper<Map> {

    public DemoMapSqlMapper() {
        super(Map.class);

        getMd().setTableName("t_user");
    }

    public Long selectTotal(QueryCondition qc) {
        BoundSql boundSql = getBoundSql(QueryResource.select(getMd().getTableName()).add("count(*)"), qc);
        Collection<Long> totalColl = getSqlExecutor().executeSelect(getMd(), boundSql, Long.class);
        return CollectionUtils.findFirst(totalColl);
    }

    public PageResult<Map> selectPage(PageCondition condition) {
        Long total = selectTotal(condition.getQueryCond());

        QueryResource qr = QueryResource.select(getMd().getTableName());
        qr.add("id");
        qr.add("pid");
        qr.add("user_name");
        qr.add("age");
        List<Map> coll = new ArrayList<>(select(qr, condition));

        PageResult<Map> result = new PageResult<>();
        result.setPageNum(condition.getPageNum());
        result.setPageSize(condition.getPageSize());
        result.setHasNext(total > ((long) condition.getPageNum() * condition.getPageSize()));
        result.setTotalCount(total);
        result.setData(coll);
        return result;
    }

    public List<Map> selectAll() {
        QueryResource qr = QueryResource.select(getMd().getTableName());
        qr.add("id");
        qr.add("pid");
        qr.add("user_name");
        qr.add("age");
        return select(qr, null);
    }
}
